<template>
  <div>
    <TopFilter
      ref="conditionFilter"
      :list="searchList"
      :cols="3"
      labelWidth="120"
      @filterChange="changeHandle"
    />
    <FilterTable
      ref="table"
      selectionType="multiple"
      :columns="tableColumns"
      :isSelectColumn="isSelectColumn"
      :fetchapi="fetchApi"
      :params="searchData"
      :datakey="'records'"
      :onRowSelectChange="selectChange"
      :onColumnsChange="tableColumns => this.tableColumns = tableColumns"
      columnsRef="projectOperating_material_departmentService_index_01"
    >
      <template slot="controls">
        <el-button
          size="small"
          type="primary"
          icon="el-icon-plus"
          @click="drawerHandle(null,'add')"
        >新增</el-button>
        <el-button
          size="small"
          type="primary"
          icon="el-icon-download"
          :loading="exportLoading"
          @click="requestExportData"
        >下载</el-button>
        <el-button
          size="small"
          type="primary"
          icon="el-icon-upload"
          :loading="exportLoading1"
          @click="requestExportDataDemo"
        >导出模板</el-button>
        <el-button size="small" type="primary" icon="el-icon-upload" @click="importFun()">数据导入</el-button>
        <el-button size="small" type="primary" icon="el-icon-check" @click="batchHand">批量提报</el-button>
        <el-button size="small" type="primary" icon="el-icon-close" @click="batchty">批量停用</el-button>
        <!-- <el-button size="small" type="primary" icon="el-icon-plus" @click="openDialog()" >新增dialog</el-button> -->
      </template>
    </FilterTable>
    <!-- 右侧浮动 -->
    <Drawer
      :visible.sync="visibleDrawer"
      :title="dialogTitleAdd"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <info-modal
        :type="handleTypeAdd"
        v-model="initData"
        :rowData="formData"
        @close="closeHandler"
      />
    </Drawer>

    <!-- 导入按钮 -->
    <BaseDialog
      :visible.sync="isimportpop"
      destroyOnClose
      title="数据导入"
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <ImoprtModal
        menuId="-1"
        url="/api/cmscloud.market/material/import"
        @close="closeHandler('','refresh')"
      />
    </BaseDialog>
  </div>
</template>

<script>
import { exportExcelFile, formatdateByDay } from '@/utils/index';
import { dictionary } from '@/utils/dictMixin';
import {
  getMaterialList,
  getmaterialTypeOneList,
  getMaterialExcelList,
  getMaterialExcelDemoList,
  selectMaterialListByBill,
  batchHandAll,
  batchtyAll
} from '@/api/cms-api/projectOperating/program/push';
import infoModal from './info';
import ImoprtModal from '@/pages/cms-common/import';
export default {
  mixins: [dictionary],
  components: {
    infoModal,
    ImoprtModal
  },
  data() {
    return {
      searchList: this.getSearchList(), //搜索框配置
      tableColumns: this.getTableColumns(),
      isSelectColumn: true,
      visibleDrawer: false,
      initData: {},
      visibleDialog: false,
      fetchApi: getMaterialList, //调用API
      searchData: { IsinitParam: 1 }, //搜索数据
      visibleDrawer: false,
      exportLoading: false,
      exportLoading1: false,
      formData: {},
      handleTypeAdd: '',
      idsOK: [], //批量提报的ids
      isimportpop: false, //导入弹窗默认关闭
      dialogTitleAdd: '', //弹出标题
      statusOK: [] //批量选中数据的状态
    };
  },
  methods: {
    //数据导入
    importFun() {
      this.isimportpop = true;
    },
    //批量停用
    async batchty() {
      let result = {};
      if (this.idsOK.length > 0) {
        for (let i = 0; i < this.statusOK.length; i++) {
          if (this.statusOK[i] != 25361003) {
            this.$notify.warning({ title: '提示信息', message: '只有状态为“已下发”的营销素材才能进行批量停用！' });
            return;
          }
        }
        this.$confirm('确定批量停用吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          result = await batchtyAll(this.idsOK);
          if (result.resultCode === 200) {
            this.$notify.success({ title: '提示信息', message: '批量停用成功!' });
            this.searchData = { ...this.searchData };
          } else {
            this.$notify.error({ title: '提示信息', message: res.errMsg || '批量停用失败!' });
          }
        });
      } else {
        this.$notify.warning({ title: '提示信息', message: '只有状态为“已下发”的营销素材才能进行批量停用，请勾选营销素材' });
      }
    },
    //批量提报
    async batchHand() {
      let result = {};
      if (this.idsOK.length > 0) {
        for (let i = 0; i < this.statusOK.length; i++) {
          if (this.statusOK[i] != 25361001) {
            this.$notify.warning({ title: '提示信息', message: '只有状态为“未提报”的营销素材才能进行批量提报！' });
            return;
          }
        }
        this.$confirm('确定批量提报吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          result = await batchHandAll(this.idsOK);
          if (result.resultCode === 200) {
            this.$notify.success({ title: '提示信息', message: '批量提报成功!' });
            this.searchData = { ...this.searchData };
          } else {
            this.$notify.error({ title: '提示信息', message: res.errMsg || '批量提报失败!' });
          }
        });
      } else {
        this.$notify.warning({ title: '提示信息', message: '只有状态为“未提报”的营销素材才能进行批量提报，请勾选营销素材' });
      }
    },
    //选中
    selectChange(rows) {
      this.selectedRows = rows;
      let ids = []; //批量提报的ids
      for (let j = 0; j < this.selectedRows.length; j++) {
        ids.push(this.selectedRows[j].materialId);
      }
      let statusSelect = []; //批量选中数据的状态
      this.idsOK = ids;
      //选中数据的状态
      for (let k = 0; k < this.selectedRows.length; k++) {
        statusSelect.push(this.selectedRows[k].materialStatus);
      }
      this.statusOK = statusSelect;
    },
    //数据导出
    async requestExportData() {
      let r = await this.$refs.conditionFilter.GET_FORM_DATA();
      let p = null;
      if (r != null && r.length > 1) {
        p = r[1];
      }
      this.exportLoading = true;
      if (p.materialStatus == 25361001 || p.materialStatus == null) {
        p = Object.assign({}, { IsinitParam: 1 }, p);
      }
      getMaterialExcelList(p).then(res => {
        exportExcelFile(res.data, '营销素材维护');
        this.exportLoading = false;
      });
    },
    //导出模板
    requestExportDataDemo() {
      this.exportLoading1 = true;
      // this.$refs.conditionFilter.SUBMIT_FORM();
      getMaterialExcelDemoList(this.searchData).then(res => {
        exportExcelFile(res.data, '营销素材维护模板');
        this.exportLoading1 = false;
      });
    },
    //搜索
    getSearchList() {
      return [
        { type: 'INPUT', label: '营销素材代码', fieldName: 'materialCode', placeholder: '请输入...' },
        { type: 'INPUT', label: '营销素材名称', fieldName: 'materialName', placeholder: '请输入...' },
        {
          type: 'SELECT',
          label: '营销素材状态',
          fieldName: 'materialStatus',
          placeholder: '请选择...',
          itemList: this.createDictList('2536')
        },
        {
          type: 'SELECT',
          label: '营销素材类型-一级',
          fieldName: 'materialTypeOne',
          placeholder: '请选择...',
          itemList: [],
          change: value => {
            this.initmaterialTypeTwo(value);
          }
        },
        {
          type: 'SELECT',
          label: '营销素材类型-二级',
          fieldName: 'materialTypeTwo',
          placeholder: '请选择...',
          itemList: [],
          change: value => {
            this.initmaterialTypeThree(value);
          }
        },
        {
          type: 'SELECT',
          label: '营销素材类型-三级',
          fieldName: 'materialTypeThree',
          placeholder: '请选择...',
          itemList: [],
          change: value => {
            this.initmaterialTypeFour(value);
          }
        },
        {
          type: 'SELECT',
          label: '营销素材类型-四级',
          fieldName: 'materialTypeFour',
          placeholder: '请选择...',
          itemList: [],
          change: value => {
            this.initmaterialTypeFive(value);
          }
        },
        { type: 'SELECT', label: '营销素材类型-五级', fieldName: 'materialTypeFive', placeholder: '请选择...', itemList: [] }
      ];
    },
    //取营销素材类型-一级
    async initmaterialTypeOne() {
      let res = [];
      this.dataParams = { parentTypeId: '' };
      let rd = await getmaterialTypeOneList(this.dataParams);
      for (let i in rd.data) {
        res.push({ text: rd.data[i].materialTypeName, value: rd.data[i].materialTypeId });
      }
      this.searchList.find(item => item.fieldName === 'materialTypeOne').itemList = res;
      // this.searchList[3].itemList = res;
    },
    //取营销素材类型-二级
    async initmaterialTypeTwo(parentTypeId) {
      this.searchList.find(item => item.fieldName === 'materialTypeTwo').initialValue = '';
      this.searchList.find(item => item.fieldName === 'materialTypeThree').initialValue = '';
      this.searchList.find(item => item.fieldName === 'materialTypeFour').initialValue = '';
      this.searchList.find(item => item.fieldName === 'materialTypeFive').initialValue = '';
      this.searchList.find(item => item.fieldName === 'materialTypeTwo').itemList = [];
      this.searchList.find(item => item.fieldName === 'materialTypeThree').itemList = [];
      this.searchList.find(item => item.fieldName === 'materialTypeFour').itemList = [];
      this.searchList.find(item => item.fieldName === 'materialTypeFive').itemList = [];
      if (parentTypeId != '') {
        let res = [];
        this.dataParams = { parentTypeId: parentTypeId };
        let rd = await getmaterialTypeOneList(this.dataParams);
        for (let i in rd.data) {
          res.push({ text: rd.data[i].materialTypeName, value: rd.data[i].materialTypeId });
        }
        this.searchList.find(item => item.fieldName === 'materialTypeTwo').itemList = res;
      }
    },
    //取营销素材类型-三级
    async initmaterialTypeThree(parentTypeId) {
      this.searchList.find(item => item.fieldName === 'materialTypeThree').initialValue = '';
      this.searchList.find(item => item.fieldName === 'materialTypeFour').initialValue = '';
      this.searchList.find(item => item.fieldName === 'materialTypeFive').initialValue = '';
      this.searchList.find(item => item.fieldName === 'materialTypeThree').itemList = [];
      this.searchList.find(item => item.fieldName === 'materialTypeFour').itemList = [];
      this.searchList.find(item => item.fieldName === 'materialTypeFive').itemList = [];
      if (parentTypeId != '') {
        let res = [];
        this.dataParams = { parentTypeId: parentTypeId };
        let rd = await getmaterialTypeOneList(this.dataParams);
        for (let i in rd.data) {
          res.push({ text: rd.data[i].materialTypeName, value: rd.data[i].materialTypeId });
        }
        this.searchList.find(item => item.fieldName === 'materialTypeThree').itemList = res;
      }
    },
    //取营销素材类型-四级
    async initmaterialTypeFour(parentTypeId) {
      this.searchList.find(item => item.fieldName === 'materialTypeFour').initialValue = '';
      this.searchList.find(item => item.fieldName === 'materialTypeFive').initialValue = '';
      this.searchList.find(item => item.fieldName === 'materialTypeFour').itemList = [];
      this.searchList.find(item => item.fieldName === 'materialTypeFive').itemList = [];
      if (parentTypeId != '') {
        let res = [];
        this.dataParams = { parentTypeId: parentTypeId };
        let rd = await getmaterialTypeOneList(this.dataParams);
        for (let i in rd.data) {
          res.push({ text: rd.data[i].materialTypeName, value: rd.data[i].materialTypeId });
        }
        this.searchList.find(item => item.fieldName === 'materialTypeFour').itemList = res;
      }
    },
    //取营销素材类型-五级
    async initmaterialTypeFive(parentTypeId) {
      this.searchList.find(item => item.fieldName === 'materialTypeFive').initialValue = '';
      this.searchList.find(item => item.fieldName === 'materialTypeFive').itemList = [];
      if (parentTypeId != '') {
        let res = [];
        this.dataParams = { parentTypeId: parentTypeId };
        let rd = await getmaterialTypeOneList(this.dataParams);
        for (let i in rd.data) {
          res.push({ text: rd.data[i].materialTypeName, value: rd.data[i].materialTypeId });
        }
        this.searchList.find(item => item.fieldName === 'materialTypeFive').itemList = res;
      }
    },
    //表单变更时赋值
    // changeHandle(data) {
    //   this.searchData = Object.assign(data);
    //   // this.searchData = Object.assign(data);
    //   console.log(data);
    // },
    changeHandle(data) {
      if (data.materialStatus == 25361001 || data.materialStatus == null) {
        data = Object.assign({}, { IsinitParam: 1 }, data);
      }
      this.searchData = Object.assign({}, data);
    },
    getTableColumns() {
      return [
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 100,
          fixed: 'left',
          render: (props, h) => {
            if (props.row.materialStatus == '25361001' || props.row.materialStatus == '25361004') {
              return (
                <div>
                  <el-button size="mini" type="text" onClick={() => this.drawerHandle(props.row, 'edit')}>
                    编辑
                  </el-button>
                  <el-divider direction="vertical" />
                  <el-button size="mini" type="text" onClick={() => this.drawerHandle(props.row, 'show')}>
                    明细
                  </el-button>
                </div>
              );
            } else {
              return (
                <div>
                  <el-button size="mini" type="text" onClick={() => this.drawerHandle(props.row, 'show')}>
                    明细
                  </el-button>
                </div>
              );
            }
          }
        },
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '营销素材状态',
          dataIndex: 'materialStatus',
          sorter: true,
          render: props => {
            //编码转汉字
            return <span>{this.createDictText(props.row.materialStatus, '2536')}</span>;
          }
        },
        { title: '营销素材代码', dataIndex: 'materialCode', sorter: true },
        { title: '营销素材名称', dataIndex: 'materialName', sorter: true },
        // {
        //   title: '营销素材类型-一级',
        //   dataIndex: 'materialTypeOne',
        //   sorter: true,
        //   hidden: true
        // },
        // {
        //   title: '营销素材类型-二级',
        //   dataIndex: 'materialTypeTwo',
        //   sorter: true,
        //   hidden: true
        // },
        // {
        //   title: '营销素材类型-三级',
        //   dataIndex: 'materialTypeThree',
        //   sorter: true,
        //   hidden: true
        // },
        // {
        //   title: '营销素材类型-四级',
        //   dataIndex: 'materialTypeFour',
        //   sorter: true,
        //   hidden: true
        // },
        // {
        //   title: '营销素材类型-五级',
        //   dataIndex: 'materialTypeFive',
        //   sorter: true,
        //   hidden: true
        // },
        {
          title: '营销素材类型-一级',
          dataIndex: 'materialTypeOneName',
          sorter: true
        },
        {
          title: '营销素材类型-二级',
          dataIndex: 'materialTypeTwoName',
          sorter: true
        },
        {
          title: '营销素材类型-三级',
          dataIndex: 'materialTypeThreeName',
          sorter: true
        },
        {
          title: '营销素材类型-四级',
          dataIndex: 'materialTypeFourName',
          sorter: true
        },
        {
          title: '营销素材类型-五级',
          dataIndex: 'materialTypeFiveName',
          sorter: true
        },
        // { title: '来源部门', dataIndex: 'sourceDept', sorter: true, hidden: true },
        { title: '来源部门', dataIndex: 'orgName', sorter: true },
        // { title: '经销商代码', dataIndex: 'ownerCode', sorter: true, hidden: true },
        {
          title: '是否需要反馈',
          dataIndex: 'isNeedFeedback',
          sorter: true,
          render: props => {
            //编码转汉字
            return <span>{this.createDictText(props.row.isNeedFeedback, '1004')}</span>;
          }
        },
        {
          title: '反馈截止日期',
          dataIndex: 'feedbackEndDate',
          sorter: true,
          render: props => {
            if (props.row.feedbackEndDate == null) {
              return <div style="text-align:center">---</div>;
            } else {
              return <span>{formatdateByDay(props.row.feedbackEndDate)} </span>;
            }
          }
        }
      ];
    },
    // formatDates: function(value) {
    //   // 这里的 value 就是需要过滤的数据
    //   if (value == null || value == '') {
    //     return '';
    //   }
    //   var date = new Date(value);
    //   var year = date.getFullYear();
    //   var month = date.getMonth() + 1;
    //   var day = date.getDate();
    //   return year + '-' + month + '-' + day;
    // },
    openDialog() {
      this.visibleDialog = true;
    },
    // closeDialog(data) {
    //   this.visibleDialog = false; //关闭弹窗
    //   //返回数据逻辑自己写
    //   console.log(data);
    // },
    closeDialog(param) {
      this.$emit('close', false, param);
    },
    //详情
    async drawerHandle(row, type) {
      //逻辑自己写
      // this.initData = {
      //   type: type, //add/edit/show
      //   id: 1001
      // }; //行id
      //新增
      if (type === 'add') {
        this.handleTypeAdd = 'add';
        this.dialogTitleAdd = `营销素材新增`;
        this.visibleDrawer = true;
      }
      //编辑
      if (type === 'edit') {
        let res = {};
        this.handleTypeAdd = 'edit';
        this.dialogTitleAdd = `营销素材编辑`;
        this.formData = row;
        let fileParams = { materialId: this.formData.materialId, billType: 25721001 };
        res = await selectMaterialListByBill(fileParams);
        if (res.data.length > 0) {
          let caseUrlList = [];
          for (let j = 0; j < res.data.length; j++) {
            let o1 = { name: res.data[j].fileName };
            let o2 = { url: res.data[j].fileId };
            let a = Object.assign(o1, o2);
            caseUrlList.push(a);
          }
          this.formData = Object.assign({}, { caseUrl: caseUrlList }, this.formData);
        }
        this.visibleDrawer = true;
      }
      //明细
      if (type === 'show') {
        let res = {};
        this.handleTypeAdd = 'show';
        this.dialogTitleAdd = `营销素材明细`;
        this.formData = row;
        let fileParams = { materialId: this.formData.materialId, billType: 25721001 };
        res = await selectMaterialListByBill(fileParams);
        if (res.data.length > 0) {
          let caseUrlList = [];
          for (let j = 0; j < res.data.length; j++) {
            let o1 = { name: res.data[j].fileName };
            let o2 = { url: res.data[j].fileId };
            let a = Object.assign(o1, o2);
            caseUrlList.push(a);
          }
          this.formData = Object.assign({}, { caseUrl: caseUrlList }, this.formData);
        }
        this.visibleDrawer = true;
      }
    },
    //关闭详情
    closeHandler(val, type) {
      this.visibleDrawer = false;
      this.isimportpop = false;
      if (type === 'refresh') {
        // 重新加载
        this.searchData = { ...this.searchData };
      }
    }
  },
  mounted() {
    //初始化营销素材类型-一级
    this.initmaterialTypeOne();
    // this.searchData = { IsinitParam: 1 };
  }
};
</script>

<!--style scoped>
    .cover-container{
        width:70vw !important;
    }
</style -->
<style>
.cover-container {
  width: 70vw !important;
}
</style>
